<template>
  <div style='height: 100%;'>
    <div v-show='index'>
      <Row class='page-title-wrapper'>
        <Col :lg='{span:6}' >
          <div class='page-title'>
            <h3>施工评定表</h3>
          </div>
        </Col>
        <Col :lg='{span:18}'  class='padding-left'>
          <div class='search-form-wrapper'>
            <Form :model='searchForm' class='search-form' inline ref='searchForm'>
              <div>
                <FormItem prop='type'>
                  <Select filterable placeholder='请选择类别' v-model='searchForm.type'>
                    <Option :key='item.id' :value='item.id' v-for='item in typeList'>{{ item.name }}</Option>
                  </Select>
                </FormItem>
                <FormItem prop='name'>
                  <Input placeholder='请输入名称或者编号' v-model='searchForm.name' />
                </FormItem>
              </div>
              <FormItem>
                <Button @click='handleSearchClick' type='primary'>查询</Button>
                <Button @click='handleResetForm' style='margin-right: 10px;'>重置</Button>
                <Button :disabled='sonData.noLength' @click='printReport' ghost type='primary' style='margin-right: 10px;' >打印</Button>
                <Button :disabled='contractData.noLength' @click='printContractReport(true)' style='margin-right: 10px;' ghost type='primary'>打印合同</Button>
                <Button :disabled='contractData.noLength' style='margin-right: 10px;' @click='exportContractReport(true)' ghost type='primary'>导出签名pdf
                </Button>
                <Button :disabled='sonData.noLength'  @click='exportReport(true)' ghost type='primary' style='margin-right: 10px;'>导出Pdf</Button>
                 <Button :disabled='sonData.noLength'  @click='exportReport(false)' ghost type='primary' class='btnstye1'>
                  导出Excel
                </Button>
              </FormItem>
            </Form>
          </div>
        </Col>
      </Row>
      <!-- <template> -->
      <Row class='app_table_div'>
        <Col :lg='{span:6}' :md='{span:6}' class='padding-right my-scollor'>
          <div class='section-title'>
            <h3>{{ projectName }}</h3>
            <div class='tree'>
              <Tree :data='treeData' :render='renderContent'></Tree>
            </div>
          </div>
        </Col>
        <Col :lg='{span:18}' :md='{span:18}' class='padding-left'>
          <!-- <div class="table-output-button-group">

          </div> -->
          <div>
            <Table
              :columns='columns4'
              :data='data1'
              @on-selection-change='getSelect'
              border
              ref='selection'
              stripe
            >
              <template slot='joint' slot-scope='{ row }'>
                <strong style='color: #000;'>{{ row.okreport }}</strong>
                <!-- <strong style="color: #000;">{{row.totalreport}}</strong><strong style="color: red;">({{ row.okreport }})</strong> -->
              </template>
              <template slot='action' slot-scope='{ row }'>
                <Button
                  v-permission='"cevaluation:edit"'
                  @click='change(1, row.nodeId, row.id,row)'
                  size='small'
                  style='margin-right: 5px;'
                  type='primary'
                  :class="handleCanEidt(row)?'':'my-disabled'"
                >编辑
                </Button>
                <Button
                  @click='change(0, row.nodeId, row.id,row)'
                  size='small'
                  style='margin-right: 5px;'
                  type='primary'
                >查看
                </Button>
              </template>
            </Table>
            <Page
              :page-size='pageSize'
              :total='totalItem'
              @on-change='pageChange'
              @on-page-size-change='pageSizeChange'
              show-sizer
              show-total
              style='float:right;margin-top:20px'
            />
          </div>
        </Col>
        <template>
          <!-- 施工合同段弹框 -->
          <Modal title='施工合同段详情' v-model='contractDetails'>
            <Form
              :label-width='80'
              :model='formValidate_contractDetails'
              ref='formValidate_contractDetails'
            >
              <FormItem label='施工合同段' prop='name'>
                <Input disabled v-model='formValidate_contractDetails.name'></Input>
              </FormItem>
              <FormItem label='编码' prop='prefix'>
                <Input disabled v-model='formValidate_contractDetails.prefix'></Input>
              </FormItem>
              <FormItem label='起止桩号' prop='qqzh'>
                <Input disabled v-model='formValidate_contractDetails.qqzh'></Input>
              </FormItem>
              <FormItem label='施工单位' prop='sgdw_name'>
                <Input disabled v-model='formValidate_contractDetails.sgdw_name'></Input>
              </FormItem>
              <FormItem label='监理单位' prop='jldw_name'>
                <Input disabled v-model='formValidate_contractDetails.jldw_name'></Input>
              </FormItem>
            </Form>
          </Modal>
          <!-- 其他层级弹框 -->
          <Modal title='其他层级详情' v-model='modalOther'>
            <Form :label-width='80' :model='formValidate_contractDetails'>
              <FormItem label='层级' prop='levelName'>
                <Input disabled v-model='formValidate_contractDetails.levelName'></Input>
              </FormItem>
              <FormItem label='类型' prop='levelType'>
                <Input disabled v-model='formValidate_contractDetails.levelType'></Input>
              </FormItem>
              <FormItem label='编号' prop='fullcode'>
                <Input disabled v-model='formValidate_contractDetails.fullcode'></Input>
              </FormItem>
              <FormItem label='名称' prop='nodeName'>
                <Input disabled v-model='formValidate_contractDetails.nodeName'></Input>
              </FormItem>
              <FormItem label='排序' prop='sort'>
                <Input disabled v-model='formValidate_contractDetails.sort'></Input>
              </FormItem>
            </Form>
          </Modal>
        </template>
      </Row>
      <!-- </template> -->
    </div>
    <div style='height: 100%;' v-show='!index'>
      <div class='header'>
        <h3>施工评定表</h3>
        <template>
          <div class='btn-group'>
            <Button @click='index = true'>返回</Button>
            <Button @click="saveFooter('formValidate')" type='primary'>保存</Button>
            <Button @click='submitPrimaryApproval' type='primary' v-if='provalBtn'>提交审批</Button>
          </div>
        </template>
      </div>
      <section style='position: relative;'>
        <div style='height: 100%;' v-if='!single'>
          <tHeader
            :fxgcName='theaderObj.fxgcName'
            :fxgcNum='theaderObj.fxgcNum'
            :gcbw='theaderObj.gcbw'
            :h1='theaderObj.h1'
            :nodeId='nodeId'
            :reportId='reportId'
            :sgCompany='theaderObj.sgCompany'
            :ssdwName='theaderObj.ssdwName'
            :ssfbName='theaderObj.ssfbName'
            :ssjsProject='theaderObj.ssjsProject'
            :myReruqest='myReruqest'
            @changeRequest='changeRequest'
          />
          <iframe
            :src='srcrpx'
            frameborder='0'
            id='iframe'
            scrolling='no'
            style='border: none; width: 100%; height: calc(100vh - 164px);'
          ></iframe>
          <tFooter
            ref='tFooter'
            :formFooter='tfooterObj'
            :nodeId='nodeId'
            :reportId='reportId'
            @changeResult='changeResult'
            @on-success='handleSuccess'
          />

        </div>
        <div style='height: 100%;' v-if='single'>
          <iframe
            :src='srcrpx'
            frameborder='0'
            id='iframe'
            scrolling='no'
            style='border: none; width: 100%; height: calc(100vh - 164px);'
          ></iframe>
        </div>
      </section>

    </div>
    <!-- 侧边栏组件 -->
    <ApprovalSidebar
      v-show='!index'
      :id='approval.approvalDataId'
      :nodeId='nodeId'
      :flowType='2'
      :type='approval.approvalType'
      @is-approval-has='handleApprovalHasChange'
      model='default'
      ref='approvalSidebar'
    />
  </div>
</template>
<script>
import apiObj from '@/api/manage-construction.js';
import outputObj from '@/api/output.js';

import tHeader from '../../../common_components/table-header-pd';
import tFooter from '../../../common_components/table-footer-pd';
import { getProject, getToken } from '@/libs/util';

import ApprovalSidebar from '@/components/approval-sidebar/index.js';
import { ApprovalType, DevPrefixReport } from '@/config/cfg.js';
import { getCheckTypeList } from '@/api/common.js';
import { batchDownload } from '@/api/qiyuesuo.js';

export default {
  name: 'evaluate_prg',
  components: {
    tHeader,
    tFooter,
    ApprovalSidebar
  },
  data () {
    return {
      searchForm: {
        type: '',
        name: ''
      },
      myReruqest: '',
      projectName: getProject(),

      typeList: [], // 类型选择项

      index: true,
      provalBtn: false,
      active: false,
      pList: [
        {
          title: '监理评定表',
          check: true
        },
        {
          title: '施工评定表',
          check: false
        }
      ],

      // 润乾报表1地址
      src1: '',
      // 润乾报表2地址
      src2: '',
      single: false,
      // 报表头组件数据
      theaderObj: {
        h1: '',
        fxgcName: '',
        fxgcNum: '',
        sgCompany: '',
        ssjsProject: '',
        ssfbName: '',
        ssdwName: '',
        gcbw: ''
      },
      // 报表尾组件数据
      tfooterObj: {
        zhiliang_baozheng_ziliao: '',
        waiguan_zhiliang: '',
        riqi: '',
        jilu: '',
        fuhe: '',
        gongcheng_zhiliang_dengji_pingding: '',
        jiance: '',
        jiance_fuzeren: '',
        jiben_yaoqiu: ''
      },
      // 子组件审批列表
      approved_List: [],
      showTable: true,
      // 施工合同段详情弹出框
      contractDetails: false,
      // 其他弹框
      modalOther: false,
      // 施工合同段表单对象
      formValidate_contractDetails: {},

      // nodeId
      nodeId: 0,
      reportId: 0,
      // nodeType
      nodeType: 0,

      tableData: [],

      // 初始项目树
      treeData: [],

      columns4: [
        { type: 'selection', width: 60, align: 'center' },
        // { title: '工序字段', key: 'gxname' },
        { title: '分项工程', key: 'fxname' },
        { title: '序号', key: 'number' },
        { title: '检查表', slot: 'joint', key: 'total' },
        { title: '录入人员', key: 'username' },
        { title: '录入时间', key: 'date' },
        { title: '状态', key: 'state' },
        { title: '操作', slot: 'action', width: 150, align: 'center' }
      ],
      data1: [],
      // 总条数/页码/页条数
      totalItem: 0,
      pageNum: 1,
      pageSize: 10,
      sonData: {
        outputList: [],
        noLength: true
      },
      contractData: {
        outputList: [],
        noLength: true
      },
      srcrpx: '',
      srcsht: '',
      // 审批相关
      approval: {
        approvalDataId: '', // 审批数据id
        approvalType: ApprovalType.SP_TYPE_SGPD // 审批数据类型
      },
      report_node_id: 0,
      dataId: '',
      filename: '',
      selectNodeId: '', // 树节点选中的id
      headers: ''
    };
  },
  methods: {
    exportContractReport () {
      let param = {};
      // param.contractIds = '3040566452467749481';
      let cs = this.contractData.outputList.map((item) => item.contractId);
      param.contractIds = cs.join(',');
      batchDownload(param).then(response => {
        // eslint-disable-next-line standard/object-curly-even-spacing
        let blob = new Blob([response.data], { type: 'application/zip' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'files.zip');
        document.body.appendChild(link);
        link.click();
      });
    },
    // 项目树(不可编辑)
    renderContent (h, { root, node, data }) {
      return h(
        'span',
        {
          style: {
            display: 'inline-flex',
            width: '100%',
            justifyContent: 'space-between'
          },

          class:
            data.nodeClick === true ? 'tree-item  level-click' : 'tree-item '
        },
        [
          h(
            'span',
            {
              style: {
                display: 'inline-flex',
                lineHeight: '23px',
                cursor: 'pointer',
                whiteSpace: 'normal',
                alignItems: 'center'
              },
              class: 'tree-text',
              on: {
                click: () => {
                  for (let i = 0; i < root.length; i++) {
                    root[i].node.nodeClick = false;
                  }
                  data.nodeClick = true;
                  this.selectNodeId = data.nodeId;
                  this.nodeId = data.nodeId;
                  this.getTableList();
                }
              }
            },
            [
              h('Icon', {
                // props: {
                //   type: 'ios-paper-outline'
                // },
                class: `iconfont ${this.getLevelIcon(node.node.nodeType)}`,

                style: {
                  margin: '0 5px',
                  fontSize: '16px',
                  verticalAlign: 'middle'
                }
              }),
              h('span', data.nodeName)
            ]
          ),
          h(
            'span',
            {
              style: {
                display: 'inline-block',
                marginLeft: '32px'
              },
              class: 'tree-item-btn'
            },
            [
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  size: 'small',
                  type: 'text'
                }),
                style: {
                  color: 'rgb(90, 111, 206)',
                  padding: '1px 3px 10px',
                  marginRight: '30px'
                },
                domProps: {
                  innerHTML: '查看'
                },
                on: {
                  click: () => {
                    this.nodeId = data.nodeId;
                    this.nodeType = data.nodeType;
                    this.typeModel(data.nodeType, data.nodeId);
                  }
                }
              })
            ]
          )
        ]
      );
    },
    saveFooter (form) {
      this.$refs.tFooter.saveFooter(form);
    },
    handleCanEidt (row) {
      return ['流程发起', '未录入'].includes(row.state);
    },
    // 根据当前项目树层级返回icon图标
    getLevelIcon (type) {
      const icons = [
        'icon-xingzhuangjiehe',
        'icon-hetong2',
        'icon-a-xingzhuangjiehe2',
        'icon-xingzhuangjiehebeifen',
        'icon-a-Fill12',
        'icon-a-Fill1beifen',
        'icon-a-Fill5',
        'icon-buwei',
        'icon-gongxu'
      ];
      return icons[type - 2];
    },
    // 根据层级类型判断弹出框
    async typeModel (nodeType, nodeId) {
      nodeType === 2 ? (this.contractDetails = true) : (this.modalOther = true);
      const send = {
        nodeId,
        nodeType
      };
      try {
        const resp = await apiObj.viewContractDetails(send);
        const datas = resp.data.data;
        this.formValidate_contractDetails = datas;
      } catch (error) {
        console.error('error', error);
      }
    },
    // 报表详情页面请求
    async editTableList (nodeId, reportId) {
      const send = { nodeId: nodeId, reportId: reportId };
      try {
        const resp = await apiObj.editTableList(send);
        this.headers = resp.data.data.head;
        const thObj = this.theaderObj;
        console.log(resp.data.data.head, 'resp.data.data.head');
        const {
          fxname, reportName, htd_name = '', projectName, sgdw, fbname, dwname,
          fullcode, gcbw, report_node_id, reportId, dataId, url, token, filename
        } = resp.data.data.head;
        this.tfooterObj = resp.data.data.footer || this.tfooterObj;
        this.tfooterObj.filename = filename;
        this.tfooterObj.dataId = dataId;
        this.myReruqest = this.tfooterObj.jiben_yaoqiu || '';

        thObj.fxgcName = fxname;
        thObj.h1 = reportName;
        thObj.sgCompany = sgdw;
        thObj.ssjsProject = projectName + htd_name;
        thObj.ssfbName = fbname;
        thObj.ssdwName = dwname;
        thObj.fxgcNum = fullcode;
        thObj.gcbw = gcbw || '';
        this.approval.approvalDataId = report_node_id;
        this.filename = filename;
        this.dataId = dataId;

        this.srcrpx = `${DevPrefixReport + url}showReport.jsp?rpx=/view/${filename}_view.rpx&arg1=${dataId}&token=${token}&display=${this.single ? 1 : 0}&fenxiang_id=${nodeId}&fullcode=${fullcode}&reportId=${reportId}&scale=1.3`;
      } catch (error) {
      }
    },
    // 查看/编辑事件
    change (type, nodeId, reportId, row) {
      this.nodeId = nodeId;
      this.reportId = reportId;
      this.editTableList(nodeId, reportId);
      if (type === 1) {
        if (!this.handleCanEidt(row)) {
          this.$Message.warning('流程审批中，不可编辑');
        } else {
          this.index = false;
          this.provalBtn = true;
          this.single = false;
        }
      } else {
        this.index = false;
        this.provalBtn = false;
        this.single = true;
      }
    },
    // 提交审批：把报表和审批流程提交
    async submitPrimaryApproval () {
      const approvalList = this.$refs.approvalSidebar.getApprovalData();
      const { filename, dataId, nodeId, reportId } = this.headers;
      const _url = `?report=%7B/view/${filename}_view.rpx(arg1=${dataId};pid=${nodeId},${reportId};token=${getToken()};tid=${nodeId};)%7D`;
      if (approvalList && approvalList.length === 0) {
        this.$Modal.warning({
          title: '提示',
          content: '请至少添加一个审批节点'
        });
      } else {
        const send = {
          busVo: {
            dataid: this.approval.approvalDataId
          },
          list: approvalList,
          fileDTO: {
            uploadUrl: _url,
            fileName: filename
          }
        };
        try {
          const resp = await apiObj.submitApprovalBtnSGPD(send);
          console.log('提交审批后的resp', resp);
          this.index = true;
          this.getTableList();
        } catch (error) {
        }
      }
    },
    // 判断当前报表的审批状态
    handleApprovalHasChange (isHas) {
      this.provalBtn = !isHas;
    },

    // 获取合同段列表下面项目树接口
    async initRenderTree () {
      try {
        const resp = await apiObj.getContractTree();
        const treeData = resp.data.data;
        // 处理数据
        const handleTerrData = treeDate => {
          treeDate.forEach(node => {
            this.$set(node, 'nodeClick', false);
            // node.expand = true;
            if (node.children) {
              handleTerrData(node.children);
            }
          });
        };

        handleTerrData(treeData);
        this.treeData = treeData;
      } catch (error) {
        console.log('error', error);
      }
    },
    // 获取分项工程table列表接口
    async getTableList (id) {
      try {
        const pramas = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        };
        if (this.searchForm.type) {
          pramas.levelTypeId = this.searchForm.type;
        }
        if (this.searchForm.name) {
          pramas.tableName = this.searchForm.name;
        }
        if (this.selectNodeId) {
          pramas.nodeId = this.selectNodeId;
        }
        const resp = await apiObj.getTableListSG(pramas);
        const { total, data } = resp.data;
        this.totalItem = total;
        this.data1 = data;
      } catch (error) {
        console.error('error', error);
      }
    },
    getSelect (selectList) {
      console.info(selectList);
      this.sonData.outputList = selectList;
      selectList.length === 0
        ? (this.sonData.noLength = true)
        : (this.sonData.noLength = false);
      let cs = selectList.filter(item => item.contractId != null && item.contractId !== '');
      this.contractData.outputList = cs;
      cs.length === 0
        ? (this.contractData.noLength = true)
        : (this.contractData.noLength = false);
    },
    async printReport () {
      const type = 'rareport';
      const list = this.sonData.outputList;

      try {
        const resp = await outputObj.printR(type, list, true);
        console.log('resp', resp);
      } catch (error) {
      }
    },
    // 合同打印
    async printContractReport () {
      let req = {};
      let cs = this.contractData.outputList.map((item) => item.contractId);
      req.contractId = cs.join(',');
      let res = await getPrintUrl(req);
      if (res.data.code === '0') {
        const link = document.createElement('a');
        link.href = res.data.data;
        link.setAttribute('target', '_blank');
        document.body.appendChild(link);
        link.click();
      }
    },
    async exportReport (pdf) {
      const type = 'rareport';
      const list = this.sonData.outputList;

      try {
        const resp = await outputObj.exportR(type, list, pdf, true);
        console.log('resp', resp);
      } catch (error) {
      }
    },
    // 页码切换（上一页下一页）
    pageChange (page) {
      this.pageNum = page;
      this.getTableList();
    },
    // 页条数切换
    pageSizeChange (size) {
      this.pageSize = size;
      this.getTableList();
    },
    handleResetForm () {
      this.$refs.searchForm.resetFields();
      this.getTableList();
    },
    handleSearchClick () {
      this.selectNodeId = '';

      const handleTerrData = treeDate => {
        treeDate.forEach(node => {
          node.nodeClick = false;
          if (node.children) {
            handleTerrData(node.children);
          }
        });
      };
      handleTerrData(this.treeData);
      this.getTableList();
    },
    async getCheckTypeList () {
      const resp = await getCheckTypeList();
      // console.log('typelist', JSON.stringify(resp, 2, 2));
      this.typeList = resp.data.data;
    },
    // 表头子组件修改基本要求
    changeRequest (value) {
      this.myReruqest = value;
      this.tfooterObj.jiben_yaoqiu = value;
    },
    // 表尾子组件修改评定结果
    changeResult (value) {
      this.tfooterObj.gongcheng_zhiliang_dengji_pingding = value;
    },
    // 保存成功后的返回
    handleSuccess () {
      this.index = true;
    }

  },
  mounted () {
    this.initRenderTree();
    this.getTableList();
    this.getCheckTypeList();
  }
};
</script>
<style lang='less' scoped>
.main .content-wrapper {
  overflow-x: hidden;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;

  .btn-group {
    button {
      margin-right: 10px;
    }
  }

  .p-title {
    width: 15%;
    display: flex;
    align-items: center;
    justify-content: space-around;

    p {
      width: 100%;
      border-bottom: 1px solid black;
      text-align: center;
      line-height: 40px;
      box-sizing: border-box;
    }

    p:hover {
      cursor: pointer;
    }

    .p-active {
      color: #2d8cf0;
      border-bottom: 2px solid #2d8cf0;
    }
  }
}

.search-form {
  display: flex;
  justify-content: space-between;

  .ivu-input {
    width: 160px;
  }

  .ivu-select {
    width: 160px;
  }

  .ivu-btn:first-child {
    margin-right: 10px;
  }

  > .ivu-form-item:last-child {
    margin-right: 0;
  }
}

.table-output-button-group {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;

  .ivu-btn {
    margin-left: 10px;
  }
}

.btnstyle {
  margin: 0px 10px;
}

/deep/ .level-click {
  .tree-text {
    padding: 0px 8px;
    background: rgb(90, 111, 206);
    border-radius: 3px;
    color: #fff !important;
  }
}

/deep/ .tree-item {
  .ivu-btn {
    visibility: hidden;
  }
}

/deep/ .tree-item:hover {
  .tree-text {
    color: rgb(90, 111, 206);
  }

  .ivu-btn {
    visibility: visible;
  }
}

/deep/ .ivu-tree-arrow i {
  margin-bottom: 8px
}

/deep/ .ivu-table-cell.ivu-table-cell-with-selection {
  text-overflow: clip;
}

table {
  border-collapse: inherit
}

@import '../../../assets/css/hoverscollor.css';
.my-disabled {
  color: #c5c8ce;
  background-color: #f7f7f7;
  border-color: #dcdee2
}
</style>
